package com.ytjj.qmyx.admin.service.impl;

import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.constants.RedisKeyConstant;
import com.ytjj.common.enums.AliPayComplaintsStatusEnums;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.model.YxAlipayConfig;
import com.ytjj.common.service.AlipayService;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.DateTimeUtil;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.common.utils.OrderUtils;
import com.ytjj.common.utils.feishu.FeiShuUtil;
import com.ytjj.qmyx.admin.config.SupplyApiConfig;
import com.ytjj.qmyx.admin.dao.*;
import com.ytjj.qmyx.admin.eunm.ActivityEnums;
import com.ytjj.qmyx.admin.eunm.ExpressNameCode;
import com.ytjj.qmyx.admin.mapper.*;
import com.ytjj.qmyx.admin.model.*;
import com.ytjj.qmyx.admin.model.OrdersDelay;
import com.ytjj.qmyx.admin.model.request.*;
import com.ytjj.qmyx.admin.model.response.*;
import com.ytjj.qmyx.admin.model.response.OrderDisparitiesRefundResponse;
import com.ytjj.qmyx.admin.service.AdminService;
import com.ytjj.qmyx.admin.service.CustomerService;
import com.ytjj.qmyx.admin.service.MemberService;
import com.ytjj.qmyx.admin.service.ReturnGoodsService;
import com.ytjj.qmyx.admin.utils.UserUtil;
import com.ytjj.qmyx.mall.client.MallClient;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.BankerRequest;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.mall.model.BankerResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@RefreshScope
@Slf4j
public class CustomerServiceImpl implements CustomerService {

    @Resource
    private CustomerDao customerDao;
    @Autowired
    private OrderNoteDao orderNoteDao;
    @Autowired
    private MemberService memberService;
    @Resource
    private OrdersInfoMapper ordersInfoMapper;
    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private OrdersDao ordersDao;
    @Resource
    private ReturnRegisterDao returnRegisterDao;
    @Resource
    private SupplyApiConfig supplyApiConfig;
    @Resource
    private OrdersDelayMapper ordersDelayMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ReturnGoodsService returnGoodsService;
    @Autowired
    private ReissueLogisticsDao reissueLogisticsDao;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private ReissueHistoryMapper reissueHistoryMapper;
    @Resource
    private AlipayService alipayService;
    @Resource
    private MallClient mallClient;
    @Resource
    private OrderDisparitiesRefundMapper orderDisparitiesRefundMapper;
    @Resource
    private ReissueLogisticsMapper reissueLogisticsMapper;
    @Resource
    private ProductSpecMapper productSpecMapper;
    @Resource
    private UpdateProductSpecRecordMapper updateProductSpecRecordMapper;
    @Resource
    private OrderProblemMessageMapper orderProblemMessageMapper;
    @Resource
    private OrdersPayMapper ordersPayMapper;
    @Resource
    private ComplaintsRecordsMapper complaintsRecordsMapper;
    @Resource
    private AlipayComplaintsRecordsMapper alipayComplaintsRecordsMapper;
    /**
     * 开始时间限制开关 0-开启 1-关闭
     */
    @Value("${switch.startTime:1}")
    private Integer startTimeSwitch;

    @Override
    public CommonPage<CustomerResponse> getCustomerOrderList(CustomerRequest customerRequest) {
        PageHelper.startPage(customerRequest.getPageNum(),customerRequest.getPageSize());
        List<CustomerResponse> pageList = customerDao.getCustomerOrderList(customerRequest);
        pageList.stream().forEach(s -> {
            StringBuilder goodsPrice = new StringBuilder("");
            if (ActivityEnums.CASH_SCORE.getActivityCode().equals(s.getActivityType())) {
                goodsPrice.append("积分" + s.getActivityMax());
            } else if (ActivityEnums.CASH_COUPON.getActivityCode().equals(s.getActivityType())) {
                goodsPrice.append("优惠券" + s.getActivityMax());
            } else if (ActivityEnums.OLD_FOR_NEW.getActivityCode().equals(s.getActivityType())) {
                goodsPrice.append("补贴" + s.getActivityMax());
            }

            if (BigDecimal.ZERO.compareTo(null == s.getDeductionMoney() ? BigDecimal.ZERO : s.getDeductionMoney()) < 0) {
                goodsPrice.append(StringUtils.isEmpty(goodsPrice) ? "余额" : "+余额" + s.getDeductionMoney() + "元");
            }

            s.setGoodsPrice(goodsPrice.toString());
        });
        return CommonPage.restPage(pageList);
    }

    @Override
    public CommonPage<CustomerNewResponse> getNewCustomerOrderList(CustomerNewRequest request) {
//        String redisInvalidFlagKeyVal = redisService.get(RedisKeyConstant.CUSTOMER_ORDER_LIST_INVALID_FLAG);

        //加缓存
//        String redisKey = "customer:order:list:" + request.hashCode();
//        String redisValue = redisService.get(redisKey);
//        if (!StringUtils.isEmpty(redisValue) && !"0".equals(redisInvalidFlagKeyVal)) {
//            System.out.println("=============命中缓存了===============");
//            CommonPage result = JSONObject.parseObject(redisValue, CommonPage.class);
//            return result;
//        }

        if (!org.springframework.util.StringUtils.isEmpty(request.getBuyer())){
            BankerRequest request1 = new BankerRequest();
            request1.setBuyer(request.getBuyer());
            String json1 = JSON.toJSONString(request1);
            String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/banker/getBankerIdsByBankerMsg", json1, supplyApiConfig.getHeadsMap());
            List<Integer> bankerIds = JSONObject.parseArray(result, Integer.class);
            if (org.springframework.util.CollectionUtils.isEmpty(bankerIds)){
                return CommonPage.restPage(new ArrayList<>());
            }
            request.setBankerIds(bankerIds);
        }

        if (StringUtil.isNotEmpty(request.getResOrderNo())){
            String orderNo = customerDao.selectOrderInfoIdByResOrderNo(request.getResOrderNo());
            if ( org.apache.commons.lang3.StringUtils.isBlank(orderNo)) {
                return CommonPage.restPage(new ArrayList<>());
            }
            request.setOrderNo(orderNo);
        }

        if (null == request.getStartTime() && startTimeSwitch != 1) {
            LocalDate ld = LocalDate.now(ZoneId.systemDefault());
            ld = ld.plusMonths(-1);
            Instant instant = ld.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
            Date oneMonthBeforeDate = Date.from(instant);
            request.setStartTime(oneMonthBeforeDate);
        }
        PageHelper.startPage(request.getPageNum(),request.getPageSize());
        List<CustomerNewResponse> pageList = customerDao.getNewCustomerOrderList(request);
        if (CollectionUtils.isEmpty(pageList)){
            return CommonPage.restPage(new ArrayList<>());
        }
        List<String> childOrderNoList = pageList.stream().filter(item -> !StringUtils.isEmpty(item.getChildOrderNo())).map(CustomerNewResponse::getChildOrderNo).collect(Collectors.toList());
        List<Integer> bankerIdList = pageList.stream().filter(item -> null != item.getBankerId()).map(CustomerNewResponse::getBankerId).collect(Collectors.toList());
        List<BankerResponse> bankerResponses = getBankerResponses(bankerIdList);

        List<Integer> productIdList = pageList.stream().filter(item -> null != item.getProductId()).map(CustomerNewResponse::getProductId).collect(Collectors.toList());
        ProductExample example = new ProductExample();
        example.createCriteria().andIdIn(productIdList);
        List<Product> products = productMapper.selectByExample(example);
        List<Integer> supplyProductIds = products.stream().filter(item -> null != item.getSupplyProductId()).map(Product::getSupplyProductId).collect(Collectors.toList());

        List<YxProduct> yxProducts = new ArrayList<>();
        if (!org.springframework.util.CollectionUtils.isEmpty(supplyProductIds)){
            ProductReceiveRequest productReceiveRequest = new ProductReceiveRequest();
            productReceiveRequest.setProductIds(supplyProductIds);
            String json = JSON.toJSONString(productReceiveRequest);
            String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/getByIds", json, supplyApiConfig.getHeadsMap());
            yxProducts = JSONObject.parseArray(result, YxProduct.class);
        }


        List<ReissueLogistics> reissueLogistics = reissueLogisticsDao.selectByChildOrderNoList(childOrderNoList);
        List<ReissueHistoryResponse> histories = reissueHistoryMapper.queryHistory(childOrderNoList);
        /**
         * 查询供应商订单是否已导出
         */
        List<OrderQueryResponse> bankerOrderQueryResultList = returnGoodsService.querySupplyChainOrderInfo(childOrderNoList);
        //查订单运费
        List<OrdersInfoFreight> list = new ArrayList<>();
        List<OrderProblemMessage> orderProblemMessages = new ArrayList<>();
        if (!CollectionUtils.isEmpty(childOrderNoList)) {
            list = customerDao.selectFreightByChildOrderNoList(childOrderNoList);
            //查询订单问题消息
            orderProblemMessages = orderProblemMessageMapper.queryByChildOrderNoList(childOrderNoList);
        }

        //查询客服备注和订单异常备注
        List<Integer> orderInfoIdList = pageList.stream().map(CustomerNewResponse::getOrderInfoId).collect(Collectors.toList());
        List<OrderNoteResponse> orderNoteList = orderNoteDao.getOrderNoteListByOrderInfoIdList(orderInfoIdList);
        List<OrderExceptionNoteResponse> orderExceptionNotes = selectNoteByChildrenOrderNo(childOrderNoList);

        //已退差价
        List<String> orderNoList = pageList.stream().filter(item -> !StringUtils.isEmpty(item.getOrderNo())).map(CustomerNewResponse::getOrderNo).collect(Collectors.toList());
        List<OrderDisparitiesRefund> orderDisparitiesRefunds = orderDisparitiesRefundMapper.querySuccessByOrderNos(orderNoList);

        //存在投诉的订单
        Set<String> orderNos = pageList.stream().map(CustomerNewResponse::getOrderNo).collect(Collectors.toSet());
        List<OrdersPay> ordersPays = ordersPayMapper.selectResOrderNoByOrderNo(new ArrayList<>(orderNos),2);
        List<OrderComplainResponse> complainResponses = new ArrayList<>();
        if(!CollectionUtils.isEmpty(ordersPays)){
            complainResponses = complaintsRecordsMapper.getComplaintsByPayNos(ordersPays.stream().map(OrdersPay::getResOrderNo).collect(Collectors.toList()));
        }
        List<OrdersInfoFreight> finalList = list;

        //重新定义变量
        List<YxProduct> finalYxProducts = yxProducts;
        List<OrderProblemMessage> finalOrderProblemMessages = orderProblemMessages;
        List<OrderComplainResponse> finalComplainResponses = complainResponses;
        pageList.stream().forEach(s -> {
            List<OrderQueryResponse> bankerOrderMatchResults =
                    bankerOrderQueryResultList.stream().filter(bankerOrder ->bankerOrder.getChildOrderNo().equals(s.getChildOrderNo())).collect(Collectors.toList());
            OrderQueryResponse bankerOrderMatchResult = null;
            if (!CollectionUtils.isEmpty(bankerOrderMatchResults)) {
                bankerOrderMatchResult = bankerOrderMatchResults.get(0);
            }
            if (null != bankerOrderMatchResult && 1 != s.getIsExport()) {
                s.setIsExport(bankerOrderMatchResult.getIsExport().intValue());
            }
            if(null != bankerOrderMatchResult){
                s.setOrderSyncTime(bankerOrderMatchResult.getOrderSyncTime());
                s.setDeliveryRemark(bankerOrderMatchResult.getDeliveryRemark());
            }

            List<BankerResponse> bankerList = bankerResponses.stream().filter(response -> response.getBankerId().equals(s.getBankerId())).collect(Collectors.toList());
            if (!org.springframework.util.CollectionUtils.isEmpty(bankerList)){
                s.setBankerName(bankerList.get(0).getBankerName());
                s.setBuyer(bankerList.get(0).getBuyer());
            }

            //获取订单运费
            List<OrdersInfoFreight> collect = finalList.stream().filter(item -> s.getChildOrderNo().equals(item.getChildOrderNo())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect)){
                OrdersInfoFreight ordersInfoFreight = collect.get(0);
                s.setFreight(ordersInfoFreight.getFreight());
            }

            List<OrderProblemMessage> collect2 = finalOrderProblemMessages.stream().filter(item -> s.getChildOrderNo().equals(item.getChildOrderNo())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(collect2)) {
                s.setFeedbackFlag(0);
            } else {
                s.setFeedbackFlag(collect2.get(0).getProblemStatus() == 1 ? 1 : 2);
                s.setProblemId(collect2.get(0).getProblemId());
            }


            StringBuilder goodsPrice = new StringBuilder("");
            if (ActivityEnums.CASH_SCORE.getActivityCode().equals(s.getActivityType())) {
                goodsPrice.append("积分" + s.getActivityMax());
            } else if (ActivityEnums.CASH_COUPON.getActivityCode().equals(s.getActivityType())) {
                goodsPrice.append("优惠券" + s.getActivityMax());
            } else if (ActivityEnums.OLD_FOR_NEW.getActivityCode().equals(s.getActivityType())) {
                goodsPrice.append("补贴" + s.getActivityMax());
            }

            if (BigDecimal.ZERO.compareTo(null == s.getDeductionMoney() ? BigDecimal.ZERO : s.getDeductionMoney()) < 0) {
                goodsPrice.append(StringUtils.isEmpty(goodsPrice) ? "余额" : "+余额" + s.getDeductionMoney() + "元");
            }

            s.setGoodsPrice(goodsPrice.toString());
            if (org.apache.commons.lang3.StringUtils.isNotBlank(s.getOrderPlatform())) {
                s.setGoodsPrice(s.getOrderPlatform());
            }
//            if ("https://ydjf.vipmalljf.com".equals(s.getDomainUrl())) {
//                s.setGoodsPrice("里数:" + s.getActivityMax().divide(new BigDecimal(100)).toString());
//            }
            s.setPayPrice(s.getIsPay() == 0 ? null : s.getRealTotalMoney());

            if (!CollectionUtils.isEmpty(reissueLogistics)) {
                List<ReissueLogistics> reissueLogisticsList = reissueLogistics.stream().filter(item -> item.getChildOrderNo().equals(s.getChildOrderNo())).collect(Collectors.toList());
                s.setReissueLogisticsCount(CollectionUtils.isEmpty(reissueLogisticsList) ? 0 : reissueLogisticsList.size());
                //获取补单最新一条的状态
                Optional<ReissueLogistics> maxIdObject = reissueLogisticsList.stream().max(Comparator.comparing(ReissueLogistics::getId));
                if (maxIdObject.isPresent()) {
                    ReissueLogistics result = maxIdObject.get();
                    s.setReissueStatus(result.getStatus());
                }

            }

            if (!CollectionUtils.isEmpty(histories)) {
                List<ReissueHistoryResponse> historyList = histories.stream().filter(item -> item.getChildOrderNo().equals(s.getChildOrderNo())).collect(Collectors.toList());
                s.setReissueLogisticsHistories(historyList);

            }

            if (!CollectionUtils.isEmpty(orderNoteList)) {
                List<OrderNoteResponse> orderNotes = orderNoteList.stream().filter(item -> item.getOrderInfoId().equals(s.getOrderInfoId()) && Integer.valueOf(1).equals(item.getType())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(orderNotes)) {
                    s.setServiceRemarkStr(DateTimeUtil.format(orderNotes.get(0).getCreateTime(),"yyyy-MM-dd HH:mm:ss")+ orderNotes.get(0).getContent());
                }
            }
            if (!CollectionUtils.isEmpty(orderExceptionNotes)) {
                List<OrderExceptionNoteResponse> notes = orderExceptionNotes.stream().filter(item -> item.getChildOrderNo().equals(s.getChildOrderNo())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(notes)) {
                    s.setOrderExceptionNoteStr(notes.get(0).getAdminName()+ " " + notes.get(0).getContent() +
                            " 时间为"  + DateTimeUtil.format(notes.get(0).getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
                }

            }

            if (!CollectionUtils.isEmpty(products)) {
                List<Product> collect1 = products.stream().filter(item -> item.getId().equals(s.getProductId())).collect(Collectors.toList());
                s.setSupplyProductId(CollectionUtils.isEmpty(collect1) ? 0 : collect1.get(0).getSupplyProductId());
                //设置订单销售平台
                if (!CollectionUtils.isEmpty(collect1)) {
                    Product product = collect1.get(0);
                    s.setPlatformInfo(product.getPlatformData() + (org.apache.commons.lang3.StringUtils.isNotBlank(s.getDomainUrl()) ?"_非支付宝" : "_支付宝渠道" ));
                }

            }
            if (!CollectionUtils.isEmpty(orderDisparitiesRefunds)) {
                List<OrderDisparitiesRefund> collect1 = orderDisparitiesRefunds.stream().filter(item -> item.getOrderNo().equals(s.getOrderNo())).collect(Collectors.toList());
                if (!org.springframework.util.CollectionUtils.isEmpty(collect1)) {
                   BigDecimal disparitiesRefundMoney = collect1.stream().map(item -> ObjectUtils.isEmpty(item.getAmount()) ? new BigDecimal(0) : item.getAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
                   s.setDisparitiesRefundMoney(disparitiesRefundMoney);
                }
            }


            //供应链商品id/售后地址
            List<YxProduct> collect1 = finalYxProducts.stream().filter(yxProduct -> yxProduct.getId().equals(s.getSupplyProductId())).collect(Collectors.toList());
            if (!org.springframework.util.CollectionUtils.isEmpty(collect1)){
                //售后地址
                s.setAddressInfo(collect1.get(0).getAddressInfo());

            }
            //是否存在投诉
            List<OrderComplainResponse> orderComplains = finalComplainResponses.stream().filter(e -> e.getOrderNo().equals(s.getOrderNo())).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(orderComplains)){
                List<LinkedHashMap<String,String>> complainData = new ArrayList<>();
                for (OrderComplainResponse orderComplain : orderComplains) {
                    LinkedHashMap<String,String> item = new LinkedHashMap<>();
                    String complainStatus = orderComplain.getComplainStatus();
                    item.put("complaintTime", orderComplain.getComplaintTime());
                    item.put("platForm", orderComplain.getPlatForm());
                    String complainStatusText = "";
                    if("支付宝".equals(orderComplain.getPlatForm())){
                        String msg = AliPayComplaintsStatusEnums.getMsg(complainStatus);
                        if(StringUtils.isEmpty(msg)){
                            complainStatusText = complainStatus;
                        }
                    }else if("微信".equals(orderComplain.getPlatForm())){
                        //投诉单状态 PENDING-待处理,PROCESSING-处理中,PROCESSED-已处理完成
                        if("PENDING".equals(complainStatus)){
                            complainStatusText = "待处理";
                        }else if("PROCESSING".equals(complainStatus)){
                            complainStatusText = "处理";
                        }else if("PROCESSED".equals(complainStatus)){
                            complainStatusText = "已处理完成";
                        }
                    }
                    item.put("handleInfo", complainStatusText);
                    complainData.add(item);
                }
                //投诉信息
                s.setComplainInfoList(complainData);
            }
        });
        CommonPage result = CommonPage.restPage(pageList);

        return result;
    }

    @Override
    public List<BankerResponse> getBankerResponses(List<Integer> bankerIdList) {
        BankerRequest bankerRequest = new BankerRequest();
        bankerRequest.setBankerIdList(bankerIdList);
        String json = JSON.toJSONString(bankerRequest);
        String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/getBankerMsg", json, supplyApiConfig.getHeadsMap());
        return JSONObject.parseArray(result, BankerResponse.class);
    }

    private List<OrderExceptionNoteResponse> selectNoteByChildrenOrderNo (List<String> childOrderNoList){
        OrderExceptionNoteRequest request  = new OrderExceptionNoteRequest();
        request.setChildOrderNoList(childOrderNoList);
        String json = JSON.toJSONString(request);
        String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/banker/selectNoteByChildrenOrderNo", json, supplyApiConfig.getHeadsMap());
        return JSONObject.parseArray(result, OrderExceptionNoteResponse.class);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderStatus(OrderStatusRequest orderStatusRequest) {
        //同步小记
        OrderNote orderNote = new OrderNote();
        orderNote.setOrderInfoId(orderStatusRequest.getOrderInfoId());
        if (orderStatusRequest.getOrderStatus().equals("1")) {
            orderNote.setContent("修改该订单状态为：待发货!");
        } else {
            orderNote.setContent("修改该订单状态为：无效订单!");
        }
        orderNote.setAdminId(memberService.getAdmin().getId());
        orderNote.setCreateTime(new Date());
        orderNoteDao.insertOrderNote(orderNote);

        //原路返回页订单状态同步
        // 获取主订单下子订单对应的有效订单数目
//        Integer orderId = ordersDao.getOrderId(orderStatusRequest.getOrderInfoId());
        OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(orderStatusRequest.getOrderInfoId());
        Integer orderId = ordersInfo.getOrderId();
        String childOrderNo = ordersInfo.getChildOrderNo();
        // 原路返回页 订单详情状态改变
        returnRegisterDao.syncStatus(orderStatusRequest.getOrderInfoId(), orderStatusRequest.getOrderStatus());
        // 客服订单详情页 订单详情状态改变
        customerDao.updateOrderInfoStatus(orderStatusRequest.getOrderStatus(), orderStatusRequest.getOrderInfoId());
        Integer validOrders = ordersDao.getValidOrders(orderId);
        if(validOrders == 0) {
            // 主订单改为无效订单
            returnRegisterDao.invalidOrderStatus(orderStatusRequest.getOrderInfoId());
            customerDao.invalidOrderStatus(orderStatusRequest);
        } else {
            // 主订单改为待发货
            returnRegisterDao.validOrderStatus(orderStatusRequest.getOrderInfoId());
            customerDao.validOrderStatus(orderStatusRequest);
        }

        UpdateOrderStatusRequest updateOrderStatusRequest = new UpdateOrderStatusRequest();
        updateOrderStatusRequest.setChildOrderNo(childOrderNo);
        updateOrderStatusRequest.setShopId(supplyApiConfig.getShopId());
        updateOrderStatusRequest.setOrderStatus(Integer.valueOf(orderStatusRequest.getOrderStatus()));
        String json = JSON.toJSONString(updateOrderStatusRequest);
        HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/updateOrderStatus", json, supplyApiConfig.getHeadsMap());
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addIntercept(Integer id, Integer customerId, String customerName, String remarks, String recoveryOrderNo) {
        OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(id);
        Orders orders = ordersMapper.selectByPrimaryKey(ordersInfo.getOrderId());
        OrdersIntercept ordersIntercept = new OrdersIntercept();

        ordersIntercept.setCustomerId(customerId);
        ordersIntercept.setCustomerName(customerName);
        ordersIntercept.setOrdersInfoId(id);
        ordersIntercept.setOrderId(ordersInfo.getOrderId());
        ordersIntercept.setOrderNumber(orders.getOrderNo());
        ordersIntercept.setStatus(0);
        ordersIntercept.setRemarks(remarks);
        ordersIntercept.setLaunchTime(new Date());
        ordersIntercept.setRecoveryOrderNo(recoveryOrderNo);
        int count = customerDao.addIntercept(ordersIntercept);

        //拦截时同步供应链
        String json = JSON.toJSONString(ordersIntercept);
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl()+"/order/intercept",json,supplyApiConfig.getHeadsMap());
        if(org.springframework.util.StringUtils.isEmpty(resultJson)){
            throw new ApiException("拦截失败");
        }
        CommonResult result = JSONObject.parseObject(resultJson,CommonResult.class);

        if (result.getCode() != 200){
            throw new ApiException("拦截失败");
        }

        //添加小计
        if (count > 0) {
            //操作同步订单小记
            OrderNote orderNote = new OrderNote();
            orderNote.setCreateTime(new Date());
            orderNote.setAdminId(customerId);
            orderNote.setOrderInfoId(id);
            orderNote.setContent("该订单被拦截！");
            count = orderNoteDao.insertOrderNote(orderNote);
        }
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateOrderInfo(UpdateOrderRequest updateOrderRequest) {

        OrdersInfo ordersInfo = customerDao.selectById(updateOrderRequest.getId());

        CustomerRequest customerRequest = new CustomerRequest();
        customerRequest.setOrderNo(updateOrderRequest.getOrderNo());
        List<CustomerResponse> orderList = customerDao.getCustomerOrderList(customerRequest);
        //添加小计
        for (CustomerResponse customerResponse : orderList) {
            OrderNote orderNote = new OrderNote();
            Admin admin = memberService.getAdmin();
            if(updateOrderRequest.getUserName() != null){
                if (!updateOrderRequest.getUserName().equals(customerResponse.getUserName())){
                    orderNote.setType(2);
                    String addMessage = admin.getName() + "修改了姓名 ";
                    orderNote.setContent(addMessage);
                    orderNote.setCreateTime(new Date());
                    orderNote.setOrderInfoId(updateOrderRequest.getId());
                    orderNote.setAdminId(admin.getId());
                    orderNoteDao.insertOrderNote(orderNote);
                }
            }
            if(updateOrderRequest.getUserAddress() != null) {
                if (!updateOrderRequest.getUserAddress().equals(customerResponse.getUserAddress())){
                    orderNote.setType(2);
                    String addMessage = admin.getName() + "修改了地址 ";
                    orderNote.setContent(addMessage);
                    orderNote.setCreateTime(new Date());
                    orderNote.setOrderInfoId(updateOrderRequest.getId());
                    orderNote.setAdminId(admin.getId());
                    orderNoteDao.insertOrderNote(orderNote);
                }
            }
            if(updateOrderRequest.getUserPhone() != null) {
                if (!updateOrderRequest.getUserPhone().equals(customerResponse.getUserPhone())){
                    orderNote.setType(2);
                    String addMessage = admin.getName() + "修改了手机号 ";
                    orderNote.setContent(addMessage);
                    orderNote.setCreateTime(new Date());
                    orderNote.setOrderInfoId(updateOrderRequest.getId());
                    orderNote.setAdminId(admin.getId());
                    orderNoteDao.insertOrderNote(orderNote);
                }
            }
            if (updateOrderRequest.getSmallNote() != null) {
                if (!updateOrderRequest.getSmallNote().equals(customerResponse.getSmallNote())) {
                    String addMessage = admin.getName() + "备注：" + updateOrderRequest.getSmallNote() + " ";
                    orderNote.setType(1);
                    orderNote.setContent(addMessage);
                    orderNote.setCreateTime(new Date());
                    orderNote.setOrderInfoId(updateOrderRequest.getId());
                    orderNote.setAdminId(admin.getId());
                    orderNoteDao.insertOrderNote(orderNote);
                }
            }
        }

        //订单已推送到供应商,不支持修改收件人信息。避免已发货，修改信息也没有意义了
        OrderQueryRequest orderQueryRequest = new OrderQueryRequest();
        orderQueryRequest.setChildOrderNo(Arrays.asList(ordersInfo.getChildOrderNo()));
        String jsonStr = JSONObject.toJSONString(orderQueryRequest);
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/selectByChildOrderNo", jsonStr, supplyApiConfig.getHeadsMap());
        log.info("查询到供应链订单:{}",resultJson);
        if (!org.springframework.util.StringUtils.isEmpty(resultJson)) {
            List<String> childOrderNoList = JSONArray.parseArray(resultJson, String.class);
            //在供应链已存在
            if (org.springframework.util.CollectionUtils.isEmpty(childOrderNoList)){
                Orders orders = ordersMapper.selectByPrimaryKey(ordersInfo.getOrderId());
                if(!orders.getUserPhone().equals(updateOrderRequest.getUserPhone()) && StringUtils.isEmpty(updateOrderRequest.getSmallNote())){
                    throw new ApiException("修改收件人手机号，请填写备注！");
                }
                if (!orders.getUserName().equals(updateOrderRequest.getUserName())
                        || !orders.getUserAddress().equals(updateOrderRequest.getUserAddress())) {
                    throw new ApiException("订单已推送到供应商不支持修改收件人信息或者商品规格，请联系供应商!");
                }
            } else {
                //保存修改订单规格记录
                ProductSpec productSpec = productSpecMapper.selectByPrimaryKey(updateOrderRequest.getProductSpecId());
                log.info("修改订单规格productSpecId:{},productSpec:{},订单规格:{}",updateOrderRequest.getProductSpecId(),JSON.toJSONString(productSpec),ordersInfo.getProductSkuSpec());
                if (!ordersInfo.getProductSkuSpec().equals(productSpec.getSkuSpec())) {
                    UpdateProductSpecRecord record = new UpdateProductSpecRecord();
                    record.setAdminId(updateOrderRequest.getAdminId());
                    record.setBeforeProductSkuSpec(ordersInfo.getProductSkuSpec());
                    record.setAfterProductSkuSpec(productSpec.getSkuSpec());
                    record.setCreateTime(new Date());
                    record.setReissueLogisticsId(null);
                    record.setOrderInfoId(updateOrderRequest.getId());
                    record.setUpdateType(2);
                    updateProductSpecRecordMapper.insert(record);
                    ordersInfoMapper.updateOrderInfoProductSpec(updateOrderRequest.getId(),updateOrderRequest.getProductSpecId(),productSpec.getSkuSpec());
                }
            }

        }

        updateOrderRequest.setOrderId(ordersInfo.getOrderId());
        int updateOrders = customerDao.updateOrders(updateOrderRequest);

        // 同步至 “供应商异常订单跟踪页” 的备注中
        Map map = new HashMap<>();
        map.put("childOrderNo", ordersInfo.getChildOrderNo());
        String result = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/synchronizationOrderException", map, supplyApiConfig.getHeadsMap());
        OrderException orderException = JSONObject.parseObject(result, OrderException.class);
        if (null != orderException && null != updateOrderRequest.getSmallNote()) {
            YxOrderExceptionNote yxOrderExceptionNote = new YxOrderExceptionNote();
            Admin admin = UserUtil.getAdmin();
            yxOrderExceptionNote.setAdminName(admin.getName());
            yxOrderExceptionNote.setContent(updateOrderRequest.getSmallNote());
            yxOrderExceptionNote.setCreateTime(new Date());
            yxOrderExceptionNote.setOrderExceptionId(orderException.getId());
            HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/banker/insertNote",
                    JSONObject.toJSONString(yxOrderExceptionNote), supplyApiConfig.getHeadsMap());
        }

        try {
            UpdateOrderInfoRequest updateOrderInfoRequest = new UpdateOrderInfoRequest();
            updateOrderInfoRequest.setChildOrderNo(ordersInfo.getChildOrderNo());
            updateOrderInfoRequest.setUserName(updateOrderRequest.getUserName());
            updateOrderInfoRequest.setUserTel(updateOrderRequest.getUserPhone());
            updateOrderInfoRequest.setDeliveryAddress(updateOrderRequest.getUserAddress());
            updateOrderInfoRequest.setNote(updateOrderRequest.getSmallNote());
            String json = JSON.toJSONString(updateOrderInfoRequest);
            HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/updateOrderInfo", json, supplyApiConfig.getHeadsMap());
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 备注信息同步订单详情
        OrdersInfo info = new OrdersInfo();
        info.setId(ordersInfo.getId());
        info.setServiceRemark(updateOrderRequest.getSmallNote());
        ordersDao.updateServiceRemark(info);

        redisService.set(RedisKeyConstant.CUSTOMER_ORDER_LIST_INVALID_FLAG, "0");
        return updateOrders;
    }

    @Override
    public List<CustomerNewResponse> newOrderExportList(CustomerNewRequest request) {
        //加缓存
        String redisKey = "customer:order:export:" + request.hashCode();
        String redisValue = redisService.get(redisKey);
        if (!StringUtils.isEmpty(redisValue)) {
            List<CustomerNewResponse> list = JSONObject.parseArray(redisValue, CustomerNewResponse.class);
            return list;
        }

        List<CustomerNewResponse> list = customerDao.getNewCustomerOrderList(request);
        List<Integer> bankerIdList = list.stream().filter(item -> null != item.getBankerId()).map(CustomerNewResponse::getBankerId).collect(Collectors.toList());
        List<BankerResponse> bankerResponses = getBankerResponses(bankerIdList);
        List<String> childOrderNoList = new ArrayList<>();
        if (list.size() > 0) {
            list.stream().forEach(item -> {

                List<BankerResponse> bankerList = bankerResponses.stream().filter(response -> response.getBankerId().equals(item.getBankerId())).collect(Collectors.toList());
                if (!org.springframework.util.CollectionUtils.isEmpty(bankerList)){
                    item.setBankerName(bankerList.get(0).getBankerName());
                }
                if(null == item.getPayPrice()){
                    item.setPayPrice(item.getProductPrice());//如果查询为空,直接获取商品售价
                }
                if (StringUtil.isNotEmpty(item.getChildOrderNo())){
                    childOrderNoList.add(item.getChildOrderNo());
                }
                item.setBankerExportTime(new Date());
//                customerDao.updateIsExport(item);
                item.setExpressCompanyNo(ExpressNameCode.getExpressName(item.getExpressCompanyNo()));
            });
        }
        try {
            UpdateOrderInfoRequest updateOrderInfoRequest = new UpdateOrderInfoRequest();
            updateOrderInfoRequest.setChildOrderNoList(childOrderNoList);
            String json = JSON.toJSONString(updateOrderInfoRequest);
            HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/updateOrderInfo", json, supplyApiConfig.getHeadsMap());
        } catch (Exception e) {
            e.printStackTrace();
        }
        redisService.set(redisKey, JSONObject.toJSONString(list));
        redisService.expire(redisKey, 2 * 60);
        return list;
    }

    @Override
    public boolean addOrderDelayRemark(OrdersDelay ordersDelay) {
        ordersDelay.setAdminId(UserUtil.getAdminId());
        int insert = ordersDelayMapper.insert(ordersDelay);
        // 同步客服小记
        OrderNote orderNote = new OrderNote();
        orderNote.setOrderInfoId(ordersDelay.getOrdersInfoId());
        orderNote.setContent("延迟发货备注:" + ordersDelay.getDelayRemark());
        orderNote.setAdminId(UserUtil.getAdminId());
        orderNote.setCreateTime(new Date());
        orderNoteDao.insertOrderNote(orderNote);

        if (1 == insert) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public CommonResult repeatOrderRefund(String orderNo) {
        List<OrdersPay> payList = ordersDao.getRepeatOrderPayList(orderNo);
//        log.info("payList,{}",JSON.toJSONString(payList));
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(payList) && payList.size()>1){
            String desc = "重复支付 平台退款";
            Orders order = ordersDao.selectByOrderNo(orderNo);
            for (OrdersPay pay : payList){
                try {
                    String refundNo = OrderUtils.getRefundCode(pay.getId());

                    if (order.getTradeNo()!=null && !order.getTradeNo().equals(pay.getResOrderNo())){
                        if ("JSAPI".equals(pay.getTradeType()) || "MWEB".equals(pay.getTradeType()) || "MWEB2".equals(pay.getTradeType())){
                            Map<String, String> response = mallClient.h5RefundOrders(pay.getTradeType(), pay.getResOrderNo(), refundNo,
                                    pay.getTotalFee(), pay.getTotalFee(), desc);
                            //如果上面调用出现错误（出错的原因：因为存在h5下单，app支付），所以这里再来做一次走APP的退款
                            if ((null == response || null == response.get("return_code"))) {
                                response = mallClient.refundOrders(pay.getTradeType(), pay.getResOrderNo(), refundNo,
                                        pay.getTotalFee(), pay.getTotalFee(), desc);
                            }
                            if (response == null ||(!"SUCCESS".equals(response.get("return_code")) &&!"PROCESSING".equals(response.get("return_code")))) {
                                FeiShuUtil.sendMsg(String.format("重复支付发起退款失败,%s",response.get("return_msg")));
                            }else {
                                //orderpay状态改成4
                                ordersDao.updateOrderPayStatus(pay.getId());
                            }
                        }
                        if ("aliPay".equals(pay.getTradeType())){
                            AlipayTradeRefundResponse response;
                            //优先从数据库配置找到对应的支付账号退
                            if (pay.getPayConfigId()!=null){
                                YxAlipayConfig alipayConfig = ordersPayMapper.findAliPayById(pay.getPayConfigId());
                                response = alipayService.refundAliPayOrderMysql(pay.getResOrderNo(), refundNo,pay.getTotalFee(), desc,alipayConfig);
                            }else{
                                response = alipayService.refundAliPayOrderOld(pay.getResOrderNo(), refundNo,
                                    pay.getTotalFee(), pay.getTotalFee(), desc,pay.getChildId());
                                //退款失败，再从第3个商户退款
                                if(!response.getMsg().equals("Success") || !response.getCode().equals("10000")){
                                    response = alipayService.refundAliPayOrder05(pay.getResOrderNo(), refundNo,
                                            pay.getTotalFee(), pay.getTotalFee(), desc);
                                }
                            }

                            if (!response.getMsg().equals("Success") || !response.getCode().equals("10000")) {
                                FeiShuUtil.sendMsg(String.format("aliPay重复支付发起退款失败,%s",response.getSubMsg()));
                            }else {
                                //orderpay状态改成4
                                ordersDao.updateOrderPayStatus(pay.getId());
                            }
                        }
                        if ("aliPay-jsApi".equals(pay.getTradeType())){
                            AlipayTradeRefundResponse response = alipayService.refundJsaApiAliPayOrder(pay.getTransactionId(), refundNo,
                                    pay.getTotalFee(), pay.getTotalFee(), desc,pay.getChildId());
                            if (!response.getMsg().equals("Success") || !response.getCode().equals("10000")) {
                                FeiShuUtil.sendMsg(String.format("aliPay-jsApi重复支付发起退款失败,%s",response.getSubMsg()));
                            }else {
                                //orderpay状态改成4
                                ordersDao.updateOrderPayStatus(pay.getId());
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("重复支付发起退款失败,{}",e);
                    FeiShuUtil.sendMsg(String.format("重复支付发起退款失败,%s",e.getMessage()));
                }
            }
        }else{
            return CommonResult.failed("此订单没有重复支付");
        }
        return CommonResult.success();
    }

    @Override
    public CommonResult disparitiesRefundConfirm(String orderNo) {
        List<OrderDisparitiesRefund> orderDisparitiesRefunds = orderDisparitiesRefundMapper.querySuccessByOrderNo(orderNo);
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(orderDisparitiesRefunds)){
            return CommonResult.success(1);
        }
        return CommonResult.success(0);
    }

    @Override
    public CommonResult disparitiesRefund(String orderNo, BigDecimal amount,Integer orderInfoId,String remark,Integer undertakeParty) {
        Assert.notNull(amount,"退差价金额不能为空");
        List<OrdersPay> payList = ordersDao.getRepeatOrderPayList(orderNo);
        if (!CollectionUtils.isEmpty(payList)) {
            OrdersPay ordersPay = payList.get(0);
            String desc = "平台退差价";
            Orders order = ordersDao.selectByOrderNo(orderNo);
            OrdersInfo ordersInfos = ordersInfoMapper.selectByPrimaryKey(orderInfoId);
            if (ordersPay.getAmount().compareTo(amount)<0) {
                throw new ApiException("退差价金额不能大于实际支付金额");
            }
            List<OrderDisparitiesRefund> orderDisparitiesRefunds = orderDisparitiesRefundMapper.querySuccessByOrderNo(orderNo);
            BigDecimal refundMoney= BigDecimal.ZERO;
            if (!org.springframework.util.CollectionUtils.isEmpty(orderDisparitiesRefunds)) {
                refundMoney = orderDisparitiesRefunds.stream().map(item -> ObjectUtils.isEmpty(item.getAmount()) ? new BigDecimal(0) : item.getAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
            }
            if (ordersPay.getAmount().subtract(refundMoney).compareTo(amount)<0) {
                throw new ApiException("退差价金额和已退差价金额不能大于实际支付金额");
            }
            try{
                Admin admin = UserUtil.getAdmin();
                //保存退差价记录
                OrderDisparitiesRefund orderDisparitiesRefund = saveOrderDisparitiesRefund(admin.getId(), admin.getName(), orderNo, ordersInfos.getChildOrderNo(),
                        ordersPay.getResOrderNo(), amount,remark,undertakeParty);
                String refundNo = OrderUtils.getRefundCode(ordersPay.getId());
                //退款金额
                Integer totalFee = amount.multiply(new BigDecimal(100)).intValue();
                if (order.getTradeNo()!=null && order.getTradeNo().equals(ordersPay.getResOrderNo())) {
                    if ("JSAPI".equals(ordersPay.getTradeType()) || "MWEB".equals(ordersPay.getTradeType()) || "MWEB2".equals(ordersPay.getTradeType())) {
                        Map<String, String> response = mallClient.h5RefundOrders(ordersPay.getTradeType(), ordersPay.getResOrderNo(), refundNo,
                                ordersPay.getTotalFee(), totalFee, desc);
                        //如果上面调用出现错误（出错的原因：因为存在h5下单，app支付），所以这里再来做一次走APP的退款
                        if ((null == response || null == response.get("return_code"))) {
                            response = mallClient.refundOrders(ordersPay.getTradeType(), ordersPay.getResOrderNo(), refundNo,
                                    ordersPay.getTotalFee(), totalFee, desc);
                        }
                        if (response == null || (!"SUCCESS".equals(response.get("return_code")) && !"PROCESSING".equals(response.get("return_code")))) {
                            orderDisparitiesRefund.setStatus(3);
                            orderDisparitiesRefundMapper.updateByPrimaryKey(orderDisparitiesRefund);
                            FeiShuUtil.sendMsg(String.format("退差价发起退款失败,%s", response.get("return_msg")));
                            return CommonResult.failed(response.get("return_msg"));
                        } else {
                            //修改退差价记录状态
                            orderDisparitiesRefund.setStatus(2);
                            orderDisparitiesRefundMapper.updateByPrimaryKey(orderDisparitiesRefund);
                        }
                    }
                    if ("aliPay".equals(ordersPay.getTradeType())) {
                        AlipayTradeRefundResponse response;
                        //优先从数据库配置找到对应的支付账号退
                        if (ordersPay.getPayConfigId()!=null){
                            YxAlipayConfig alipayConfig = ordersPayMapper.findAliPayById(ordersPay.getPayConfigId());
                            response = alipayService.refundAliPayOrderMysql(ordersPay.getResOrderNo(), refundNo,totalFee, desc,alipayConfig);
                        }else{
                            response = alipayService.refundAliPayOrderOld(ordersPay.getResOrderNo(), refundNo,
                                totalFee, totalFee, desc, ordersPay.getChildId());
                            //退款失败，再从第3个商户退款
                            if (!response.getMsg().equals("Success") || !response.getCode().equals("10000")) {
                                response = alipayService.refundAliPayOrder05(ordersPay.getResOrderNo(), refundNo,
                                        ordersPay.getTotalFee(), totalFee, desc);
                            }
                        }

                        if (!response.getMsg().equals("Success") || !response.getCode().equals("10000")) {
                            orderDisparitiesRefund.setStatus(3);
                            orderDisparitiesRefundMapper.updateByPrimaryKey(orderDisparitiesRefund);
                            FeiShuUtil.sendMsg(String.format("aliPay退差价发起退款失败,%s", response.getSubMsg()));
                            return CommonResult.failed(response.getSubMsg());
                        } else {
                            //修改退差价记录状态
                            orderDisparitiesRefund.setStatus(2);
                            orderDisparitiesRefundMapper.updateByPrimaryKey(orderDisparitiesRefund);
                        }
                    }
                    if ("aliPay-jsApi".equals(ordersPay.getTradeType())) {
                        AlipayTradeRefundResponse response = alipayService.refundJsaApiAliPayOrder(ordersPay.getTransactionId(), refundNo,
                                ordersPay.getTotalFee(), totalFee, desc, ordersPay.getChildId());
                        if (!response.getMsg().equals("Success") || !response.getCode().equals("10000")) {
                            orderDisparitiesRefund.setStatus(3);
                            orderDisparitiesRefundMapper.updateByPrimaryKey(orderDisparitiesRefund);
                            FeiShuUtil.sendMsg(String.format("aliPay-jsApi退差价发起退款失败,%s", response.getSubMsg()));
                            return CommonResult.failed(response.getSubMsg());
                        } else {
                            //修改退差价记录状态
                            orderDisparitiesRefund.setStatus(2);
                            orderDisparitiesRefundMapper.updateByPrimaryKey(orderDisparitiesRefund);
                        }
                    }
                    if("ZSY".equals(ordersPay.getTradeType())){
                        int result = mallClient.zsyRefundCJ(ordersPay.getResOrderNo(),refundNo,String.valueOf(totalFee),ordersPay.getPayTime());
                        if (result == 1){
                            orderDisparitiesRefund.setStatus(2);
                            orderDisparitiesRefundMapper.updateByPrimaryKey(orderDisparitiesRefund);
                        }else{
                            orderDisparitiesRefund.setStatus(3);
                            orderDisparitiesRefundMapper.updateByPrimaryKey(orderDisparitiesRefund);
                            log.info("退差价失败,{}",ordersPay.getResOrderNo());
                            return CommonResult.failed("退差价失败,请联系管理员");
                        }
                    }
                    if ("MHKJ".equals(ordersPay.getTradeType())){
                        String result = mallClient.mhkjRefundCj(ordersPay.getResOrderNo(),refundNo,String.valueOf(totalFee),ordersPay.getPayTime());
                        if ("成功".equals(result)){
                            orderDisparitiesRefund.setStatus(2);
                            orderDisparitiesRefundMapper.updateByPrimaryKey(orderDisparitiesRefund);
                        }else{
                            orderDisparitiesRefund.setStatus(3);
                            orderDisparitiesRefundMapper.updateByPrimaryKey(orderDisparitiesRefund);
                            log.info("退差价失败,{},{}",ordersPay.getResOrderNo(),result);
                            return CommonResult.failed("退差价失败,"+result);
                        }
                    }
                }
            }catch (Exception e) {
                log.error("退差价发起退款失败,{}",e);
                FeiShuUtil.sendMsg(String.format("退差价发起退款失败,%s",e.getMessage()));
            }
        }
        return CommonResult.success();
    }
    private OrderDisparitiesRefund saveOrderDisparitiesRefund(Integer adminId, String adminName, String orderNo,
                                                              String childOrderNo, String tradeNo,
                                                              BigDecimal amount,String remark,Integer undertakeParty){
            OrderDisparitiesRefund  refund = new OrderDisparitiesRefund();
            refund.setAdminId(adminId);
            refund.setAdminName(adminName);
            refund.setAmount(amount);
            refund.setChildOrderNo(childOrderNo);
            refund.setOrderNo(orderNo);
            refund.setCreateTime(new Date());
            refund.setTradeNo(tradeNo);
            refund.setStatus(1);
            refund.setRemark(remark);
            refund.setUndertakeParty(undertakeParty);
            orderDisparitiesRefundMapper.insertSelective(refund);
            return refund;
    }

    @Override
    public CommonPage<OrderDisparitiesRefundResponse> disparitiesRefundList(OrderDispatiesRefundListRequest request) {
        PageHelper.startPage(request.getPageNum(),request.getPageSize());
        List<OrderDisparitiesRefundResponse> pageList = orderDisparitiesRefundMapper.queryByParam(request);
        if (!CollectionUtils.isEmpty(pageList)) {
            List<Integer> bankerIds = pageList.stream().filter(item -> item.getBankerId() != null).map(OrderDisparitiesRefundResponse::getBankerId).collect(Collectors.toList());
            List<Banker> bankerList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(bankerIds)) {
                Map<String, String> param = new HashMap<>();
                param.put("bankerIds", Joiner.on(",").join(bankerIds));
                String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/queryBankerByIds", param, supplyApiConfig.getHeadsMap());
                CommonResult commonResult = JSONObject.parseObject(resultJson, CommonResult.class);
                if (200 == commonResult.getCode()) {
                    bankerList = JSONArray.parseArray(commonResult.getData().toString(), Banker.class);
                }
            }
            Map<Integer, Banker> collect = bankerList.stream().collect(Collectors.toMap(Banker::getId, Function.identity()));
            for (OrderDisparitiesRefundResponse refundResponse : pageList) {
                Banker banker = collect.get(refundResponse.getBankerId());
                refundResponse.setBankerName(null != banker ? banker.getName() : null);
            }
        }
        return  CommonPage.restPage(pageList);
    }

    @Override
    public void markRefund(String childOrderNo,Integer state) {
        OrdersInfo ordersInfo = ordersInfoMapper.queryByChildOrderNo(childOrderNo);
        if (ordersInfo!=null){
            Admin admin = UserUtil.getAdmin();
            if (state==0){
                ordersInfoMapper.addMarkRerturn(ordersInfo.getId(),childOrderNo,admin.getCompellation());
            }
            if (state == 1){
                ordersInfoMapper.deleteMarkRerturn(childOrderNo);
            }
        }
    }

    @Override
    public int updateOrderProductSpec(UpdateOrderProductSpecRequest request) {
        //补单
        int result = 0;
        if (request.getUpdateType().equals(1)) {
            Integer reissueLogisticsId = request.getReissueLogisticsId();
            if (null !=reissueLogisticsId) {
                ReissueLogistics logistics = reissueLogisticsMapper.selectByPrimaryKey(reissueLogisticsId);
                ProductSpec productSpec = productSpecMapper.selectByPrimaryKey(request.getProductSpecId());
                UpdateProductSpecRecord record = new UpdateProductSpecRecord();
                record.setAdminId(request.getAdminId());
                record.setBeforeProductSkuSpec(logistics.getProductSkuSpec());
                record.setAfterProductSkuSpec(productSpec.getSkuSpec());
                record.setCreateTime(new Date());
                record.setReissueLogisticsId(reissueLogisticsId);
                record.setUpdateType(request.getUpdateType());
                record.setOrderInfoId(null);
                updateProductSpecRecordMapper.insert(record);
                result = reissueLogisticsMapper.updateReissueLogisticsProductSpec(productSpec.getSkuSpec(),reissueLogisticsId);
            }
            //订单
        } else if (request.getUpdateType().equals(2)) {
            if (request.getOrderInfoId() !=null) {
                OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(request.getOrderInfoId());
                OrderQueryRequest orderQueryRequest = new OrderQueryRequest();
                orderQueryRequest.setChildOrderNo(Arrays.asList(ordersInfo.getChildOrderNo()));
                String jsonStr = JSONObject.toJSONString(orderQueryRequest);
                String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/selectByChildOrderNo", jsonStr, supplyApiConfig.getHeadsMap());
                log.info("=========销售端存在供应链不存在的订单===========childOrderNo:{}",resultJson);
                if (!org.springframework.util.StringUtils.isEmpty(resultJson)) {
                    List<String> childOrderNoList = JSONArray.parseArray(resultJson, String.class);
                    if (!CollectionUtils.isEmpty(childOrderNoList)) {
                        ProductSpec productSpec = productSpecMapper.selectByPrimaryKey(request.getProductSpecId());
                        UpdateProductSpecRecord record = new UpdateProductSpecRecord();
                        record.setAdminId(request.getAdminId());
                        record.setBeforeProductSkuSpec(ordersInfo.getProductSkuSpec());
                        record.setAfterProductSkuSpec(productSpec.getSkuSpec());
                        record.setCreateTime(new Date());
                        record.setReissueLogisticsId(null);
                        record.setOrderInfoId(request.getOrderInfoId());
                        record.setUpdateType(request.getUpdateType());
                        updateProductSpecRecordMapper.insert(record);
                        result = ordersInfoMapper.updateOrderInfoProductSpec(request.getOrderInfoId(),request.getProductSpecId(),productSpec.getSkuSpec());

                    } else {
                        throw new ApiException("该订单已经推到供应链不能修改订单规格!");
                    }
                } else {
                    throw new ApiException("该订单已经推到供应链不能修改订单规格!");
                }
            }

        }

        return result;
    }
}
